package com.itec.learn.java.producerconsumer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 使用阻塞队列实现生产者消费者模式
 * @author chenyiqun
 */
public class ProducerConsumer {

    public static void main(String[] args) {
        BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>();
        Thread producerT = new Thread(new Producer(sharedQueue));
        Thread consumerT = new Thread(new Consumer(sharedQueue));
        producerT.start();
        consumerT.start();
    }
}

class Producer implements Runnable{
    private final BlockingQueue<Integer> sharedQueue;

    public Producer(BlockingQueue<Integer> sharedQueue){
        this.sharedQueue = sharedQueue;
    }


    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Producer: "+i);
                sharedQueue.put(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable{

    private final BlockingQueue<Integer> sharedQueue;

    public Consumer(BlockingQueue<Integer> sharedQueue){
        this.sharedQueue = sharedQueue;
    }


    @Override
    public void run() {
        while (true){
            try {
                System.out.println("Consumer: "+sharedQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
